package com.huang.redis.controller;

import cn.hutool.core.text.replacer.StrReplacer;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class IndexController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Redisson redisson;


    /*使用Redisson分布式锁的方式*/
    @GetMapping("/deduck-stock")
    public String deduckStock(){

        String lockKey="lock:product:101";
        /*加上分布式锁*/
        RLock lock = redisson.getLock(lockKey);
        lock.lock();
        try{
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock>0){
                int realStock=stock-1;
                stringRedisTemplate.opsForValue().set("stock", String.valueOf(realStock));
                System.out.println("扣减成功，库存剩余："+realStock);
            }else {
                System.out.println("扣减失败，库存不足");
            }
        }finally {
            /*解锁*/
            lock.unlock();
        }

        return "end";

    }

    /*自定义分布式锁的方式*/
    @RequestMapping("/deduct-stock2")
    public String deductStock2(){

        String lockKey="lock:product:101";
        /*生成一个随机码，防止出现线程锁误删的操作*/
        String clientId= UUID.randomUUID().toString();
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId,10, TimeUnit.SECONDS);
        if(!aBoolean){
            return "当前系统繁忙，请稍后再试";
        }

        try{
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
            if(stock>0){
                int realStock=stock-1;
                stringRedisTemplate.opsForValue().set("stock", realStock+"");
                System.out.println("扣减成功，库存剩余："+realStock);
            }else {
                System.out.println("扣减失败，库存不足");
            }
        }finally {
            /*删除锁的时候，判断是不是当前线程加的锁*/
            if(clientId.equals(stringRedisTemplate.opsForValue().get(lockKey))){
                stringRedisTemplate.delete(lockKey);
            }
        }

        return "end";
    }


}